package com.yifeng.repo.controller.postman.work.biz;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.yifeng.repo.base.utils.converter.JacksonHelper;
import com.yifeng.repo.controller.postman.configure.PostmanProperties;
import com.yifeng.repo.controller.postman.work.dto.PostTaskConf;
import org.springframework.http.MediaType;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * Created by daibing on 2023/5/10.
 */
public interface BizRequestAction<T> {

    /**
     * 支持任务自定义配置：默认是应用级别配置。
     */
    default PostTaskConf getPostTaskConf(PostmanProperties properties) {
        return new PostTaskConf(
                properties.getPostInterceptorHandler(),
                properties.getTryTimes(),
                properties.getTimeoutMillis()
        );
    }

    /**
     * 解析响应结果数据
     */
    default JsonNode parseResponseResult(Map<String, String> responseHeader, String responseBody) {
        String contentType = responseHeader.get("Content-Type");
        if (contentType.startsWith(MediaType.APPLICATION_XML_VALUE)) {
            return xml2Obj(responseBody);
        } else if (contentType.startsWith(MediaType.APPLICATION_JSON_VALUE)) {
            return JacksonHelper.toObj(responseBody);
        } else {
            return JacksonHelper.createEmptyJsonNode();
        }
    }

    /**
     * 检查响应body
     */
    default boolean checkResponseBody(JsonNode output) {
        return true;
    }

    /**
     * 检查响应签名
     */
    default boolean checkResponseSign(JsonNode output) {
        return true;
    }

    /**
     * 抽取响应数据到业务数据对象
     */
    T extractResponseData(JsonNode output);

    static JsonNode xml2Obj(String xml) {
        XmlMapper xmlMapper = new XmlMapper();
        try {
            return xmlMapper.readTree(xml.getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
